package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"product-mall/models/cache"
	"product-mall/models/mysql"
	"product-mall/pkg"
	"product-mall/productrpc/internal/svc"
	"product-mall/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *productrpc.UpdatePasswordRequest) (*productrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+"updatePassword"+in.Mobile)
	if get.Val() != in.CaptSms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号未注册")
	}

	if user.Password == pkg.Md5(in.Password) {
		return nil, fmt.Errorf("新密码不可与原密码相同")
	}

	user = mysql.User{
		Model: gorm.Model{
			ID: user.ID,
		},
		Password: pkg.Md5(in.Password),
	}
	err := mysql.DB.Debug().Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("重置密码失败")
	}

	//成功后清除短信验证码缓存
	cache.Rdb.Del(l.ctx, "sendSms"+"updatePassword"+in.Mobile)
	return &productrpc.UpdatePasswordResponse{UserId: int64(user.ID)}, nil
}
